package org.celery.core.secure.utils;

import io.jsonwebtoken.Claims;
import org.celery.core.secure.AuthMember;
import org.springblade.core.launch.constant.TokenConstant;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.utils.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Create on 2021-11-26
 *
 * @author Celery <1031868928@qq.com>
 */
public class AuthUtil {
    private static final String CELERY_MEMBER_REQUEST_ATTR = "_CELERY_MEMBER_REQUEST_ATTR_";

    private final static String HEADER = TokenConstant.HEADER;
    private final static String BEARER = TokenConstant.BEARER;
    private final static String USER_ID = TokenConstant.USER_ID;
    private final static String USER_NAME = TokenConstant.USER_NAME;
    private final static String CLIENT_ID = TokenConstant.CLIENT_ID;
    private final static Integer AUTH_LENGTH = TokenConstant.AUTH_LENGTH;

    /**
     * 获取用户信息
     *
     * @return AuthMember
     */
    public static AuthMember getMember() {
        HttpServletRequest request = WebUtil.getRequest();
        if (request == null) {
            return null;
        }
        // 优先从 request 中获取
        Object authMember = request.getAttribute(CELERY_MEMBER_REQUEST_ATTR);
        if (authMember == null) {
            authMember = getMember(request);
            if (authMember != null) {
                // 设置到 request 中
                request.setAttribute(CELERY_MEMBER_REQUEST_ATTR, authMember);
            }
        }
        return (AuthMember) authMember;
    }

    /**
     * 获取用户信息
     *
     * @param request request
     * @return BladeUser
     */
    public static AuthMember getMember(HttpServletRequest request) {
        Claims claims = getClaims(request);
        if (claims == null) {
            return null;
        }
        String clientId = Func.toStr(claims.get(AuthUtil.CLIENT_ID));
        Long userId = Func.toLong(claims.get(AuthUtil.USER_ID));
        String userName = Func.toStr(claims.get(AuthUtil.USER_NAME));
        AuthMember authMember = new AuthMember();
        authMember.setClientId(clientId);
        authMember.setUserId(userId);
        authMember.setNickname(userName);
        return authMember;
    }

    /**
     * 获取Claims
     *
     * @param request request
     * @return Claims
     */
    public static Claims getClaims(HttpServletRequest request) {
        String auth = request.getHeader(AuthUtil.HEADER);
        if (StringUtil.isNotBlank(auth) && auth.length() > AUTH_LENGTH) {
            String headStr = auth.substring(0, 6).toLowerCase();
            if (headStr.compareTo(AuthUtil.BEARER) == 0) {
                auth = auth.substring(7);
                return SecureUtil.parseJWT(auth);
            }
        } else {
            String parameter = request.getParameter(AuthUtil.HEADER);
            if (StringUtil.isNotBlank(parameter)) {
                return SecureUtil.parseJWT(parameter);
            }
        }
        return null;
    }
}
